第十一天囉~
昨天我們說到 state , 那我們如何去改變 state 呢?
當我們直接改動 state , 會發現, 畫面根本不會更新
like:
class App extends React.Component {
constructor() {
super();
this.state = {
text: 'hello',
};
}
onPressClickMe = () => {
this.state.text = 'Wow~';
};
render() {
return (
<SafeAreaView>
<View>
<Button title='Click Me!!' onPress={this.onPressClickMe} />
<Text>{this.state.text}</Text>
</View>
</SafeAreaView>
);
}
}

state 的改變需要跟隨著 component 的更新流程,這樣才會把更新的數據顯示在畫面上
那如何觸發更新流程呢?
更新指定 state , 並觸發 component 的 update 的流程
this.setState(updater, [callback]);
當下的 state & props ,可以以此為參考基礎來進行更新, return object 包裹需要更改的值callback 會在更新流程結束後去執行//object
this.setState({ text: 'hello!' });
//function
this.setState(function (state, props) {
return {
text: 'hello',
};
});
//use callback
this.setState(
function (state, props) {
return {
text: 'hello',
};
},
function () {
console.log(this.state);
}
);
所以,我們希望畫面隨著我們 state 值改變而改變,應該這樣做...
like:
class App extends React.Component {
constructor() {
super();
this.state = {
text: 'hello',
};
}
onPressClickMe = () => {
this.setState(() => {
return {
text: 'Wow~',
};
});
};
render() {
return (
<SafeAreaView>
<View>
<Button title='Click Me!!' onPress={this.onPressClickMe} />
<Text>{this.state.text}</Text>
</View>
</SafeAreaView>
);
}
}

當 component 內部進行更新流程的時候,
就會把底下有使用到的 component 一起更新
再來談到 props ,
當我們在開發時,總會考慮到 component 會在不同的情境上使用,
但是不可能把所有的邏輯都寫在 component 裡面,
這時我們就必須去靠 props 來讓外部有部分的控制權限 ,
那它的特性是:
能夠多大程度去間接影響 component 的運作props 屬性裡,以物件key-value保存props
props 值,只有在外部傳入的值發生改變時component 的 update 流程
const TextBox = () => {
return <Text>{this.props.value}</Text>;
};
const App = () => {
return (
<SafeAreaView>
<TextBox value={'Hello'} />
</SafeAreaView>
);
};